<!DOCTYPE html>
<html lang="en">
  <head>
    <meta charset="UTF-8" />
    <meta http-equiv="X-UA-Compatible" content="IE=edge" />
    <meta name="viewport" content="width=device-width, initial-scale=1.0" />
    <title>Document</title>
  </head>
  <body>
    <script>
      function fn1(cb) {
        return new Promise((resolve) => {
          setTimeout(() => {
            console.log("fn1");
            cb && cb(); // 容错
            resolve();
          }, 1000);
        });
      }

      function fn2(cb) {
        return new Promise((resolve) => {
          setTimeout(() => {
            console.log("fn2");
            cb && cb();
            resolve();
          }, 1000);
        });
      }

      function fn3(cb) {
        return new Promise((resolve) => {
          setTimeout(() => {
            console.log("fn3");
            cb && cb();
            resolve();
          }, 1000);
        });
      }

      // promise改写
      // then的链式调用，then是无限链式调用；
      fn1()
        .then(() => {
          console.log("fn1执行完毕");
          // fn2().then(() => {
          //   console.log("fn2执行完毕");
          // });
          return fn2();
        })
        .then(() => {
          console.log("fn2执行完毕");
          return fn3();
        })
        .then(() => {
          console.log("fn3执行完毕");
        });

      // 回调地狱
      fn1(function () {
        console.log("fn1执行完毕了");
        fn2(function () {
          console.log("fn2执行完毕了");
          fn3(function () {
            console.log("fn3执行完毕了");
          });
        });
      });
    </script>
  </body>
</html>
